package com.atomlab.daycheck.ui.database;

import static com.atomlab.daycheck.model.ObjectTypeInfoHelper.getObjectTypeInfo;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.atomlab.daycheck.R;
import com.atomlab.daycheck.databinding.ActivityCheckBinding;
import com.atomlab.daycheck.model.Student;
import com.atomlab.daycheck.model.personInfo;
import com.huawei.agconnect.AGConnectInstance;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;

public class CheckActivity extends AppCompatActivity {

    private static String TAG = "CheckActivity:";
    //初始化数据库
    AGConnectCloudDB mCloudDB;
    //初始化数据库配置
    CloudDBZoneConfig mConfig;
    //初始化存储区
    CloudDBZone mCloudDBZone;
    private DatabaseActivity.UiCallBack mUiCallBack = DatabaseActivity.UiCallBack.DEFAULT;

    private ActivityCheckBinding binding;
    private EditText edit_name;
    private EditText edit_phone;
    private EditText edit_address;
    private EditText edit_temperature;
    private EditText edit_inoculation;
    private CheckBox cb_green;
    private TextView button_ok;
    private Student student = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);

        binding = ActivityCheckBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.teal_200)));
            actionBar.setTitle("打卡");
        }
        edit_name = binding.editName;
        edit_phone = binding.editPhone;
        edit_address = binding.editAddress;
        edit_temperature = binding.editTemperature;
        edit_inoculation = binding.editInoculation;
        cb_green = binding.cbGreen;
        button_ok = binding.buttonOk;

        if(getIntent().getExtras() != null)
        {
            student = (Student) getIntent().getExtras().getSerializable("student");
            if(student != null)
            {
                edit_name.setText(student.getName());
                edit_phone.setText(student.getPhone());
                edit_address.setText(student.getAddress());
                edit_temperature.setText(student.getTemperature()+"");
                edit_inoculation.setText(student.getInoculation()+"");
                cb_green.setChecked(student.getGreen().equals("是"));
            }
        }
        initView();
        button_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                personInfo personInfo = new personInfo();
                if(student != null)
                {
                    personInfo.setId(student.getId());
                }
                else
                {
                    personInfo.setId(getIntent().getExtras().getInt("id",0)+1);
                }
                if(!edit_temperature.getText().toString().equals("") && !edit_inoculation.getText().toString().equals("") )
                {

                    personInfo.setName(edit_name.getText().toString());
                    personInfo.setPhone(edit_phone.getText().toString());
                    personInfo.setAddress(edit_address.getText().toString());
                    personInfo.setTemperature(Float.parseFloat(edit_temperature.getText().toString()));
                    personInfo.setInoculation(Integer.parseInt(edit_inoculation.getText().toString()));
                    personInfo.setGreen(cb_green.isChecked());
                    upsertPersonInfo(personInfo);
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        try {
            mCloudDB.closeCloudDBZone(mCloudDBZone);
        } catch (AGConnectCloudDBException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    private void initView() {

        //上一页已经初始化云数据库，这里直接 AGConnectInstance.getInstance() 获取instance
        AGConnectInstance instance = AGConnectInstance.getInstance();
        mCloudDB = AGConnectCloudDB.getInstance();
        Log.i(TAG,"The cloudDB is" + mCloudDB);
        try {
            mCloudDB.createObjectType(getObjectTypeInfo());
            mConfig = new CloudDBZoneConfig("personInfoZone",
                    CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
                    CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
            mConfig.setPersistenceEnabled(true);
            openCloudDB();
        } catch (AGConnectCloudDBException e) {
            Toast.makeText(CheckActivity.this, "initialize CloudDB failed" + e, Toast.LENGTH_LONG).show();
        }
    }

    private void openCloudDB()
    {
        Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
        openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {
            @Override
            public void onSuccess(CloudDBZone cloudDBZone) {
                Log.i("open clouddbzone", "open cloudDBZone success");
                mCloudDBZone = cloudDBZone;
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.w("open clouddbzone", "open cloudDBZone failed for " + e.getMessage());
            }
        });
    }

    public void upsertPersonInfo(personInfo personInfo) {
        if (mCloudDBZone == null) {
            Log.w(TAG, "CloudDBZone is null, try re-open it");
            return;
        }
        Task<Integer> upsertTask = mCloudDBZone.executeUpsert(personInfo);
        upsertTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
            @Override
            public void onSuccess(Integer cloudDBZoneResult) {
                try {
                    mCloudDB.closeCloudDBZone(mCloudDBZone);
                } catch (AGConnectCloudDBException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "Upsert " + cloudDBZoneResult + " records");
                Toast.makeText(CheckActivity.this, personInfo.getName()+" 打卡成功", Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                CheckActivity.this.finish();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                mUiCallBack.updateUiOnError("Insert person info failed");
                Toast.makeText(CheckActivity.this, personInfo.getName()+" 打卡失败"+"\r\n"+e, Toast.LENGTH_LONG).show();
            }
        });
    }
}